package artid.com.arttogo.view.pulllist;

import android.content.Context;
import android.util.AttributeSet;
import android.view.GestureDetector;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ListView;

public class PullableListView extends ListView implements Pullable
{
	public static Boolean isSlide=true;//用来解决滑动冲突默认可以滑动
	public static Boolean isCanPullDown=true;//是否设置下拉刷新（默认可以）
    public static Boolean isCanPullUp=true;//是否设置加载更多（默认可以）
    private GestureDetector mGestureDetector;
	View.OnTouchListener mGestureListener;
	public PullableListView(Context context)
	{
		super(context);
	}

	public PullableListView(Context context, AttributeSet attrs)
	{
		super(context, attrs);
		mGestureDetector = new GestureDetector(new YScrollDetector());
		setFadingEdgeLength(0);
	}

	public PullableListView(Context context, AttributeSet attrs, int defStyle)
	{
		super(context, attrs, defStyle);
	}

	@Override
	public boolean onInterceptTouchEvent(MotionEvent ev) {
		boolean a = super.onInterceptTouchEvent(ev);
		boolean b =mGestureDetector.onTouchEvent(ev);
		return b;
	}

	@Override
	public boolean canPullDown()
	{
		try {
			if(isCanPullDown) {
				if (isSlide) {
					if (getCount() == 0) {
						// 没有item的时候也可以下拉刷新
						return true;
					} else if (getFirstVisiblePosition() == 0
							&& getChildAt(0).getTop() >= 0) {
						// 滑到ListView的顶部了
						return true;
					} else
						return false;
				} else {
					return false;
				}
			}else {
				return false;
			}
		} catch (Exception e) {
		    // TODO: handle exception
			return false;
		}

	}

	@Override
	public boolean canPullUp()
	{
		if (isCanPullUp) {
			if (isSlide) {
				if (getCount() == 0) {
					// 没有item的时候也可以上拉加载
					return true;
				} else if (getLastVisiblePosition() == (getCount() - 1)) {
					// 滑到底部了
					if (getChildAt(getLastVisiblePosition() - getFirstVisiblePosition()) != null
							&& getChildAt(
							getLastVisiblePosition()
									- getFirstVisiblePosition()).getBottom() <= getMeasuredHeight())
						return true;
				}
				return false;
			} else {
				return false;
			}
		}else{
			return false;
		}
	}


	class YScrollDetector extends SimpleOnGestureListener {
		@Override
		public boolean onScroll(MotionEvent e1, MotionEvent e2,
								float distanceX, float distanceY) {
//			Log.d("log", "滑动监听："+Math.abs(distanceY) / Math.abs(distanceX));
			if (Math.abs(distanceY) / Math.abs(distanceX)>2) {
				return true;
			}
			isSlide=false;
			return false;
		}
	}
}
